<script lang="ts" setup>
import { getExpertList, getSearchDetail, searchList } from '~/api/home'
import type { Condition, Page } from '~/api/type'
import { getImgUrl } from '~/composables/global'
import { decode, encode } from '~/utils/base/dataEncry'

const router = useRouter()
const route = useRoute()
const dayjs = useDayjs()
const list = ref()
const TJlist = ref()
const total = ref(0)
const queryParams = reactive<{
  fclass?: string[]
  sscope?: string[]
  tdate?: string[]
  page: number
  size: number
  word: string
}
>(
  {
    page: 1,
    size: 10,
    word: '',
  },
)
const queryParamsDetail = reactive<
  {
    page: Page
    condition: Condition[]
  }
>(
  {
    page: {
      rownumber: 10,
      pageNo: 1,
    },
    condition: [],
  },
)

// console.log(route)
function clickItemSearch(item: any, item1: any) {
  const result = Object.assign({}, {
    page: 1,
    size: 10,
    word: '',
    fclass: [],
  }, item1)
  if (!result.fclass && route.query.type && route.query.type !== '全部') {
    result.fclass = [route.query.type]
  }
  if (!Array.isArray(result.sscope)) {
    if (result.sscope) {
      result.sscope = [result.sscope]
    }
    else {
      result.sscope = []
    }
  }
  if (!Array.isArray(result.fclass)) {
    if (result.fclass) {
      result.fclass = [result.fclass]
    }
    else {
      result.fclass = []
    }
  }
  result.word = item
  console.log(route.query.type)
  console.log(result)
  getData(result)
}
// 分页参数更改
function onPageChange(params: { pageNum: number, pageSize: number }) {
  queryParams.page = params.pageNum
  queryParams.size = params.pageSize
  getData(queryParams)
}
function getData(queryParams: any) {
  searchList(queryParams).then((res) => {
    list.value = []
    total.value = res.page.total
    res.data.forEach((element) => {
      const time = element.publish_time || element.modify_time
      list.value.push({
        title: element.title,
        blurd: extractTextFromPTags(element.content),
        info: element.source ? element.source : '陕西健康教育中心',
        time: dayjs(time).format('YYYY-MM-DD'),
        url: getImgUrl(element.coverimgurl),
        id: element.uidcol,
        category: element.category,
      })
    })
    TJlist.value = res.data.slice(0, 3)
  }).catch(() => {
  })
}
function extractTextFromPTags(htmlString: string) {
  const parser = new DOMParser()
  const doc = parser.parseFromString(htmlString, 'text/html')
  const pTags = doc.getElementsByTagName('p')
  let text = ''
  for (let i = 0; i < pTags.length; i++) {
    text += pTags[i]?.textContent
  }
  return text
}
onMounted(() => {
  queryParams.word = route.query.data
  if (route.query.type === '全部') {
    if (route.query.fclass) {
      queryParams.fclass = decode(route.query.fclass).fclass ? decode(route.query.fclass).fclass : ''
      queryParams.sscope = decode(route.query.fclass).sscope ? decode(route.query.fclass).sscope : ''
      queryParams.tdate = decode(route.query.fclass).tdate ? decode(route.query.fclass).tdate : ''
    }
    if (!queryParams.fclass) {
      delete queryParams.fclass
    }
    getData(queryParams)
  }
  else {
    if (route.query.fclass) {
      queryParams.fclass = decode(route.query.fclass).fclass
    }
    else {
      queryParams.fclass = [route.query.type]
    }
    getData(queryParams)
  }
})
function clickItem(item: any) {
  console.log(item)
  queryParamsDetail.condition = [{
    colName: 'uid',
    value: item.id,
    ruleType: 'eq',
  }]
  if (item?.category?.indexOf('科普专家') === 0) {
    const req = {
      condition: [{ colName: 'uid', ruleType: 'eq', value: item.id }],
    }
    getExpertList(req).then((res) => {
      navigateTo({
        path: `/peopleHealth/ExpertListDetail`,
        query: {
          id: res.data[0].id,
        },
      },{
        open:{target:"_blank"}
      })
      // navigateTo({
      //   path: `/peopleHealth/ExpertListDetail`,
      //   query: {
      //     data: encode(res.data[0]),
      //   },
      // })
    })
    return
  }
  getSearchDetail(queryParamsDetail).then((res) => {
    const resData = res.data[0]
    console.log('click-item:', resData)

    if (item?.category?.indexOf('中医科普资料') === 0 && resData?.id) {
      const url = `/peopleHealth/outKnowledgeDetail/${resData.id}&中医健康科普详情`
      navigateTo({
        path: url,
      },{
        open:{target:"_blank"}
      })
    }
    else if (route.query.type === '健康陕西') {
      // navigateTo({
      //   path: `/peopleHealth/healthyShaanxiDetail`,
      //   query: {
      //     data: encode(resData),
      //   },
      // })
      navigateTo({
        path: `/peopleHealth/healthyShaanxiDetail`,
        query: {
          id: resData.id,
        },
      },{
        open:{target:"_blank"}
      })
    }
    else if (route.query.type === '头条资讯') {
      navigateTo({
        path: `/peopleHealth/topNewsDetail`,
        // query: {
        //   data: encode(resData),
        // },
        query: {
          id: resData.id,
          // data: encode(item),
        },
      },{
        open:{target:"_blank"}
      })
    }
    else if (route.query.type === '百姓健康系列栏目') {
      navigateTo({
        // path: `/peopleHealth/peopleHealthSeriesDetail/${type}`,
        path: `/peopleHealth/peopleHealthSeriesDetail/${resData.id}`,
        query: {
          type: resData.classify_name.split('/')[1],
          // data: encode(item),
          ptUid: resData.pt_uid,

        },
      },{
        open:{target:"_blank"}
      })
      // navigateTo({
      //   path: `/peopleHealth/peopleHealthSeriesDetail/${resData.classify_name.split('/')[1]}`,
      //   query: {
      //     data: encode(resData),
      //   },
      // })
    }
    else if (route.query.type === '健康知识') {
      navigateTo({
        path: `/peopleHealth/knowledgeDetail/${resData.id}&1`,
        // query: {
        //     data: encode(resData),
        // },
      },{
        open:{target:"_blank"}
      })
    }
    else if (route.query.type === '科普资料') {
      navigateTo({
        path: `/peopleHealth/popularizationDetail/${resData.id}&${resData.classify_name.split('/')[1]}`,
        // query: {
        //     data: encode(resData),
        // },
      },{
        open:{target:"_blank"}
      })
    }
    else if (route.query.type === '宣传活动') {
      navigateTo({
        path: `/peopleHealth/HealthActivityDetail/${resData.id}&${resData.classify_name.split('/')[1]}`,
        // query: {
        //     data: encode(resData),
        // },
      },{
        open:{target:"_blank"}
      })
    }
    else if (route.query.type === '全部') {
      if (item.category.split('/')[0] === '健康陕西') {
        // navigateTo({
        //   path: `/peopleHealth/healthyShaanxiDetail`,
        //   query: {
        //     data: encode(resData),
        //   },
        // })
        navigateTo({
          path: `/peopleHealth/healthyShaanxiDetail`,
          query: {
            id: resData.id,
          },
        },{
          open:{target:"_blank"}
        })
      }
      else if (item.category === '头条资讯') {
        navigateTo({
          path: `/peopleHealth/topNewsDetail`,
          query: {
            id: resData.id,
            // data: encode(item),
          },
        },{
          open:{target:"_blank"}
        })
        // navigateTo({
        //   path: `/peopleHealth/topNewsDetail`,
        //   query: {
        //     data: encode(resData),
        //   },
        // })
      }
      else if (item.category.split('/')[0] === '百姓健康系列栏目') {
        navigateTo({
          path: `/peopleHealth/peopleHealthSeriesDetail/${resData.id}`,
          query: {
            // data: encode(resData),
            type: resData.classify_name.split('/')[1],
            ptUid: resData.pt_uid,
          },
        },{
          open:{target:"_blank"}
        })
        // navigateTo({
        //   path: `/peopleHealth/peopleHealthSeriesDetail/${resData.classify_name.split('/')[1]}`,
        //   query: {
        //     data: encode(resData),
        //   },
        // })
      }
      else if (item.category.split('/')[0] === '健康知识') {
        navigateTo({
          path: `/peopleHealth/knowledgeDetail/${resData.id}&1`,
          // query: {
          //     data: encode(resData),
          // },
        },{
          open:{target:"_blank"}
        })
      }
      else if (item.category.split('/')[0] === '科普资料') {
        navigateTo({
          path: `/peopleHealth/popularizationDetail/${resData.id}&${resData.classify_name.split('/')[1]}`,
          // query: {
          //     data: encode(resData),
          // },
        },{
          open:{target:"_blank"}
        })
      }
      else if (item.category.split('/')[0] === '宣传活动') {
        navigateTo({
          path: `/peopleHealth/HealthActivityDetail/${resData.id}&${resData.classify_name.split('/')[1]}`,
          // query: {
          //     data: encode(res.data[0]),
          // },
        },{
          open:{target:"_blank"}
        })
      }
    }
  })
}
</script>

<template>
  <div class="bg-[url('/img/index.png')] bg-#F7F9FD bg-no-repeat">
    <div class="w-100% flex justify-center">
      <div class="w-60% flex justify-center">
        <PublicSearchAll :type="route.query.type" :value="route.query.data" @click-item="clickItemSearch" />
      </div>
    </div>
    <div class="px-80">
      <div class="bg-#fff px-30px py-20px">
        <div class="mt-20px flex justify-between">
          <div class="w-100%">
            <div class="flex items-center">
              <div
                class="h-40px w-40px flex cursor-pointer items-center justify-center rounded-md"
                style="
                                background: linear-gradient(159.97deg, rgba(206,234,158,1) -140.78%,rgba(53,179,137,1) 89.45%);" @click="router.back()"
              >
                <div class="h-18px w-18px flex items-center justify-center rounded-50% bg-#fff">
                  <span class="flex items-center -ml-2px" text="#0E9472">&lt;</span>
                </div>
              </div>
              <div class="ml-5">
                为你找到相关结果约 <span class="text-#0E9472 font-700">{{ total }}</span> 个
              </div>
            </div>

            <div class="">
              <PublicList :list="list" @click-item="clickItem" />
              <PublicPagination
                :page-size="queryParams.size" :page-num="queryParams.page" :total="total"
                @change="onPageChange"
              />
            </div>
          </div>
          <!-- <div class="w-15%">
                        <div>
                            <div class=" flex items-center py-5px px-10px rounded-tr rounded-tl h-40px"
                                style="background: linear-gradient(159.97deg, rgba(206,234,158,1) -140.78%,rgba(53,179,137,1) 89.45%);">
                                <img src="/img/tj.png" alt="">
                                <div class="pl-15px " text="#fff 16px">推荐</div>
                            </div>
                            <div class="py-5px px-10px rounded-br rounded-bl" border="2px solid #50bc8d"
                                hover="text-#0E9472">
                                <div v-for="item in TJlist">
                                    <img :src="getImgUrl(item.coverimgurl)" alt="">
                                    <div class="py-10px" text="14px">{{ item.title }}</div>
                                </div>
                            </div>
                        </div>
                    </div> -->
        </div>
      </div>
    </div>
  </div>
</template>

<style></style>
